import numpy as np
from my_base_service import *
from my_prompt_template import *
from langfuse.decorators import observe

cache = {}


@observe()
def get_embeddings(text):
    """封装 OpenAI 的 Embedding 模型接口"""
    if text in cache:
        return cache[text]
    data = openai.embeddings.create(
        input=[text],
        model="text-embedding-3-small",
        dimensions=256
    ).data
    cache[text] = data[0].embedding
    return data[0].embedding


@observe()
def cos_sim(v, m):
    score = np.dot(m, v) / (np.linalg.norm(m, axis=1) * np.linalg.norm(v))
    return score.tolist()


@observe()
def check_duplicated(query, existing, threshold=0.825):
    query_vec = np.array(get_embeddings(query))
    mat = np.array([item[1] for item in existing])
    cos = cos_sim(query_vec, mat)
    return max(cos) >= threshold


need_answer_chain = (
        need_answer
        | get_model()
        | strParser
)


@observe()
def need_answer(question, outlines):
    return need_answer_chain.invoke(
        {"user_input": question, "outlines": outlines}
    ) == 'Y'


# 假设 已有问题
question_list = [
    ("LangChain可以商用吗", get_embeddings("LangChain可以商用吗")),
    ("LangChain开源吗", get_embeddings("LangChain开源吗")),
]


@observe()
def verify_question(
        question: str,
        outlines: str,
        question_list: list,
) -> bool:
    # 判断是否需要回答
    if need_answer(question, outlines):
        # 判断是否重复
        if not check_duplicated(question, question_list):
            vec = cache[question]
            question_list.append((question, vec))
            return True
    return False
